const { app, BrowserWindow, Menu, MenuItem, screen, Tray, ipcMain, webFrame } = require('electron');
const path = require('path');
const ipc_modules = require('./modules/ipc');
let win;
const right_menu = new Menu();
// const LOAD_URL = 'https://web-api.gamersky.com/webpage/mahjongPlus/';
const LOAD_URL = 'http://192.168.13.210:3301/';
// const LOAD_URL = 'http://web-test.gamersky.com/test/mj/';

const createWindow = () => {
	win = new BrowserWindow({
		frame: false,
		show: false,
		resizable: true,
		icon: path.join(__dirname, './logo/index.png'),
		webPreferences: {
			devTools: true,
			nodeIntegration: true,
			contextIsolation: false,
			zoomFactor: 1,
			defaultEncoding: 'UTF-8',
		},
		backgroundColor: '#FFF',
	});
	ipc_modules(win);
	Menu.setApplicationMenu(null);
	win.loadURL(LOAD_URL);
	win.once('ready-to-show', () => {
		win.webContents.setZoomFactor(1);
	});
	win.webContents.on('zoom-changed', (e, zd) => {
		win.webContents.zoomLevel += zd === 'in' ? 1 : -1;
	});
};

// close
app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') app.quit();
});

// open
app.whenReady().then(() => {
	createWindow();
	app.on('activate', () => {
		if (BrowserWindow.getAllWindows().length === 0) createWindow();
	});
	// 系统托盘
	let tray = new Tray(path.join(__dirname, './logo/index.png'));
	const contextMenu = Menu.buildFromTemplate([
		{
			label: '最小化',
			click: () => {
				win.minimize();
			},
		},
		{
			label: '退出',
			click: () => {
				win.close();
			},
		},
	]);
	tray.setToolTip('星皓互娱-麻将教学专用');
	tray.setContextMenu(contextMenu);
	tray.on('click', () => {
		win.isMinimized() && win.restore();
	});
	// 右键菜单
	let win_is_resizable;
	for (const menuitem of [
		{
			label: '刷新',
			click: () => {
				win.webContents.send('reload');
			},
		},
		{ type: 'separator' },
		{
			label: '关闭',
			click: () => {
				win.close();
			},
		},
	])
		right_menu.append(new MenuItem(menuitem));
	win.webContents.on('context-menu', (e, { x, y }) => {
		right_menu.popup({ window: win, x, y });
	});
});
